<script>
import * as XLSX from 'xlsx';
import * as DateUtil from '@/components/util/DateUtil'
export default {
  data() {
    return {
      tableInfo: {
        data: [],
        cashUnite: '元',
        standUnite: 'kgce'
      },
      subjectInfo: {
        label: '请选择用能主体',
        getLabel: function (arr) {
          if(!arr || arr.length < 1) {
            return '请选择用能主体'
          }
          let s = '';
          arr.forEach(function (i){
            if (s !== '') {
              s = s + ','
            }
            s = s + i.label
          })
          return s
        },
        dialogVisible: false,
        selected: [],
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      dateRange: {
        dateType: '时',
        formatDateTye: function (){
          if (this.dateType === '时') {
            return 'hour'
          }
          if (this.dateType === '日') {
            return 'day'
          }
          if (this.dateType === '月') {
            return 'month'
          }
          if (this.dateType === '年') {
            return 'year'
          }
          return ''
        },
        selected: [new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7), new Date()],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
      }
    }
  },
  mounted() {
    this.fetchTreeData()
  },
  methods: {
    fetchData: function (){
      const formatSelectedTreeNode = function (arr) {
        arr.forEach(function (item) {
          item.subjectType = item.type
          item.subjectId = item.id
          item.subjectName = item.label
        })
        return arr
      }
      const selectedList = formatSelectedTreeNode(this.subjectInfo.selected)
      if(selectedList.length < 1){
        this.$message('请选择用能主体')
        return
      }
      let dateType = this.dateRange.formatDateTye();
      let from = this.$getTimeInfo(this.dateRange.selected[0]).toMin
      let end = this.$getTimeInfo(this.dateRange.selected[1]).toMin
      if (dateType === 'hour') {
        from = this.$getTimeInfo(this.dateRange.selected[0]).toHour + ':00:00'
        end = this.$getTimeInfo(this.dateRange.selected[1]).toHour + ':59:59'
      }else if (dateType === 'day') {
        from = this.$getTimeInfo(this.dateRange.selected[0]).toDay + ' 00:00:00'
        end = this.$getTimeInfo(this.dateRange.selected[1]).toDay + ' 23:59:59'
      }else if (dateType === 'month') {
        from = this.$getTimeInfo(this.dateRange.selected[0]).toMonth + '-01 00:00:00'
        end = DateUtil.endDayOfMonth(this.dateRange.selected[1])
      }else if (dateType === 'year') {
        from = this.$getTimeInfo(this.dateRange.selected[0]).toYear + '-01-01 00:00:00'
        end = this.$getTimeInfo(this.dateRange.selected[1]).toYear + '-12-31 23:59:59'
      }
      const data = {
        content:{
          subjects: selectedList,
          dateType: dateType,
          fromDate: from,
          toDate: end,
        }
      }
      this.$axios({url:"/ems/client/energy/report/subject/energy/excel", data: data}).then((content) => {
        this.tableInfo.data = content.list
        this.tableInfo.cashUnite = content.cashUnite
        this.tableInfo.standUnite = content.standUnite
      })
    },
    fetchTreeData: function () {
      const data = {content: {excludeTypes:["METER","POINT","GATEWAY","DIAGRAM"]}}
      this.$axios({url:'/ems/client/energy/search/subject/tree',data: data}).then((content) => {
        this.subjectInfo.treeData = content.list
      });
    },
    dialogConfirm: function () {
      this.subjectInfo.dialogVisible = false
      this.subjectInfo.selected = this.$refs.tree.getCheckedNodes()
      this.subjectInfo.label = this.subjectInfo.getLabel(this.subjectInfo.selected)
    },
    handleClose() {
      this.subjectInfo.dialogVisible = false
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    treeClick: function () {
      this.dialogVisible = false
    },
    exportExcel: function () {
      const table = this.$refs.data_table_energy_excel.$el
      const ws = XLSX.utils.table_to_sheet(table)
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      XLSX.writeFile(wb, '能耗统计报表_' + new Date().getTime()+ ".xlsx");
    }
  }
}
</script>

<template>
<div>
  <el-row>
    <el-col :span="24">
      <el-button type="text" @click="subjectInfo.dialogVisible = true" style="background-color: white;width: 350px;color: rgb(192, 196, 204);">{{subjectInfo.label}}</el-button>
      <el-dialog
          title="提示"
          :visible.sync="subjectInfo.dialogVisible"
          width="30%"
          :before-close="handleClose">
        <el-tree
            class="filter-tree"
            show-checkbox
            :data="subjectInfo.treeData"
            :props="subjectInfo.defaultProps"
            :filter-node-method="filterNode"
            @node-click="treeClick"
            ref="tree">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="subjectInfo.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogConfirm">确 定</el-button>
        </span>
      </el-dialog>
      &nbsp;
      <label>时间范围：&nbsp;</label>
      <el-radio-group v-model="dateRange.dateType">
        <el-radio-button label="时"></el-radio-button>
        <el-radio-button label="日"></el-radio-button>
        <el-radio-button label="月"></el-radio-button>
        <el-radio-button label="年"></el-radio-button>
      </el-radio-group>
      &nbsp;
      <el-date-picker
          v-model="dateRange.selected"
          :type="dateRange.dateType==='时' ? 'datetimerange': (dateRange.dateType==='日' ? 'daterange':'monthrange')"
          :format="dateRange.dateType==='年' ? 'yyyy': ''"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="dateRange.pickerOptions">
      </el-date-picker>
      &nbsp;
      <el-button type="primary" @click="fetchData">查询</el-button>
      <el-button type="primary" plain @click="exportExcel" >导出</el-button>
    </el-col>
  </el-row>
  <el-row style="margin-top: 20px;">
    <el-col :span="24">
      <el-table
          :data="tableInfo.data"
          stripe
          ref="data_table_energy_excel"
          style="width: 100%">
        <el-table-column align="center" prop="id" label="序号" width="100"></el-table-column>
        <el-table-column  align="center" prop="subjectName"  label="用能主体"  width="180"> </el-table-column>
        <el-table-column  prop="meterCode" label="仪表编码" width="300"></el-table-column>
        <el-table-column  prop="meterName" label="仪表名称"> </el-table-column>
        <el-table-column prop="fromValue" label="起码（开始时间）"> </el-table-column>
        <el-table-column align="toValue" prop="time" label="止码（结束时间）"> </el-table-column>
        <el-table-column align="increaseStandValue" prop="handleStatus" label="用量（标准煤）">
          <template slot-scope="scope">{{$doubleVal(scope.row.increaseStandValue)}}&nbsp;{{tableInfo.standUnite}}</template>
        </el-table-column>
        <!--
        <el-table-column align="center" prop="increaseCashValue" label="用量（货币）">
          <template slot-scope="scope">{{$doubleVal(scope.row.increaseCashValue)}}&nbsp;{{tableInfo.cashUnite}}</template>
        </el-table-column>
        -->
        <el-table-column align="center" prop="increaseRealValue + ' ' + energyUnit" label="用量">
          <template slot-scope="scope">{{$doubleVal(scope.row.increaseRealValue)}}&nbsp;{{scope.row.energyUnit}}</template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
</div>
</template>

<style>

</style>
